package com.cybertron.am.wordpress.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cybertron.am.wordpress.domain.CrawlCategory;
import com.cybertron.am.wordpress.domain.CrawlProduct;
import com.cybertron.am.wordpress.domain.Website;
import com.cybertron.am.wordpress.persistence.CrawlCategoryMapper;
import com.cybertron.am.wordpress.persistence.CrawlProductMapper;
import com.cybertron.am.wordpress.persistence.WebsiteMapper;
import com.cybertron.am.wordpress.util.WooUtil;
import com.ne.boot.common.exception.NEError;
import com.ne.boot.common.exception.NEException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class SysService {

    @Autowired
    private WooUtil wooUtil;
    @Autowired
    private WebsiteMapper websiteMapper;
    @Autowired
    private CrawlCategoryMapper categoryMapper;
    @Autowired
    private CrawlProductMapper productMapper;

    public void addWebsite(String domain) {
        if (StringUtils.isBlank(domain)) {
            throw new NEException(NEError.INVALID_PARAMETER, "请输入域名");
        }
        String id = DigestUtils.md5Hex(domain);
        websiteMapper.deleteById(id);
        exec("wget -O /bin/wp_install.sh https://gitee.com/cybertron/am-wordpress/raw/master/wp_install.sh");
        exec("chmod +x /bin/wp_install.sh");
        exec("wp_install.sh -d " + domain);
        websiteMapper.insert(Website.builder()
                .id(DigestUtils.md5Hex(domain))
                .domain(domain)
                .title(domain)
                .build());
    }

    public void copyWebsite(String source, String target) {
        if (StringUtils.isAnyBlank(source, target)) {
            throw new NEException(NEError.INVALID_PARAMETER, "请输入源网站和目标网站");
        }
        String id = DigestUtils.md5Hex(target);
        websiteMapper.deleteById(id);
        exec("wget -O /bin/wp_copy.sh https://gitee.com/cybertron/am-wordpress/raw/master/wp_copy.sh");
        exec("chmod +x /bin/wp_copy.sh");
        exec("wp_copy.sh  -s " + source + " -t " + target);
        websiteMapper.insert(Website.builder()
                .id(id)
                .domain(target)
                .title(target)
                .build());
    }

    public void pushData(String seedDomain, String seedCategoryId, String websiteDomain) {
        if (StringUtils.isAnyBlank(seedDomain, websiteDomain)) {
            throw new NEException(NEError.INVALID_PARAMETER, "请输入数据站点和导入站点");
        }
        String seedId = DigestUtils.md5Hex(seedDomain);
        String websiteId = DigestUtils.md5Hex(websiteDomain);
        wooUtil.pushData(seedId, seedCategoryId, websiteId);
    }

    private void exec(String command) {
        CommandLine cmdLine = CommandLine.parse(command);
        DefaultExecutor exec = new DefaultExecutor();
        exec.setExitValue(0);
        try {
            int exitCode = exec.execute(cmdLine);
            log.info("执行完成{},{}", command, exitCode);
        } catch (Throwable e) {
            log.error("执行命令错误" + command, e);
        }
    }

    public String tree(String seedDomain) {
        String seedId = DigestUtils.md5Hex(seedDomain);
        StringBuffer sb = new StringBuffer();
        List<CrawlCategory> roots = categoryMapper.selectList(new LambdaQueryWrapper<CrawlCategory>()
                .eq(CrawlCategory::getSeedId, seedId)
                .isNull(CrawlCategory::getParentId)
        );
        buildTree(sb, "++", roots);
        return sb.toString();
    }

    public void buildTree(StringBuffer sb, String prefix, List<CrawlCategory> categories) {
        for (CrawlCategory category : categories) {
            Integer count = productMapper.selectCount(new LambdaQueryWrapper<CrawlProduct>()
                    .eq(CrawlProduct::getCategoryId, category.getId())
            );
            sb.append(prefix)
                    .append(category.getTitle())
                    .append("(").append(category.getId()).append(")")
                    .append("(").append(count).append(")")
                    .append("\n");
            List<CrawlCategory> child = categoryMapper.selectList(new LambdaQueryWrapper<CrawlCategory>()
                    .eq(CrawlCategory::getParentId, category.getId())
            );
            if (CollectionUtils.isEmpty(child)) {
                continue;
            }
            buildTree(sb, prefix + "++", child);
        }
    }
}
